package com.neusoft.Dao;

import com.neusoft.model.Product;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ProductDao {
    private List<Product> productList = InitData.init();
    public List<Product> selectProductList() {
        return this.productList;
    }
    public List<Product> selectProductListByName(String name) {
        List<Product> list = new ArrayList<>();
        for (Product product : this.productList) {
            if(product.getName().contains(name)){
                list.add(product);
            }
        }
        return list;
    }

    public Product selectProductById(Integer id){
        Product product=null;
        for (Product p1 : productList) {
            if (p1.getId().equals(id)) {
                    product=p1;
                    break;
            }
        }
        return product;
    }
    public int deleteProductById(Integer id){
/*        for (Product product : productList) {
            if(product.getId()==id){
                productList.remove(product);
            }
        }
        return 1;*/
        Iterator<Product> iterator = productList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getId().equals(id)) {
                iterator.remove();
            }
        }
        return 1;
    }
    public int insertProduct(Product product){
        productList.add(product);
        return 1;
    }
    public int updateProduct(Product product){
        int count=0;
        if(product==null||productList == null ){
            return 0;
        }
        for (Product p1 : productList) {
            if (p1.getId().equals(product.getId())){
                p1.setId(product.getId());
                p1.setName(product.getName());
                p1.setPrice(product.getPrice());
                count++;
                break;
            }
        }
        return count;
    }

}
